<template>
  <view class="image-uploader">
    <!-- 没有图片时显示上传按钮 -->
    <view v-if="!image" class="upload-container" @click="selectImage">
      <text class="upload-icon">+</text>
    </view>

    <!-- 有图片时显示图片和一个清除按钮 -->
    <view v-else class="image-preview">
      <image :src="image" class="uploaded-image" mode="aspectFill" />
      <view class="clear-btn" @click="clearImage">
        <text class="tn-icon tn-icon-close"></text>
      </view>
    </view>
  </view>
</template>

<script>
import {API_BASE_URL} from "@/config";

export default {
  data() {
    return {
      image: '' // 存储图片的 URL
    }
  },
  methods: {
    selectImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.image = res.tempFilePaths[0];
          uni.uploadFile({
            url:`${API_BASE_URL}/infra/file/upload`,
            filePath: this.image,
            name: 'file',
            header:{
              'Authorization': `Bearer ${uni.getStorageSync('accessToken')}`
            },
            success: (res) => {
              const data = JSON.parse(res.data);
              //上传成功。把data返回给父组件
              this.$emit('uploadSuccess', data.data)
            }
          })
        }
      });
    },
    clearImage() {
      this.image = ''; // 清除图片
    }
  }
}
</script>

<style>
.image-uploader {
  width: 100px; /* 确定组件宽度 */
  height:100px; /* 确定组件高度 */
  position: relative;
}

.upload-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #ddd;
}

.upload-icon {
  font-size: 30px;
  color: #888;
  font-weight: bold;
}

.image-preview {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.clear-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 20px;
  height: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.tn-icon-close {
  color: #fff;
  font-size: 14px;
}
</style>
